"""
@Project:p8_syl_flask
@File:users.py
@Author:郑凯乐
@Date:18:49
"""
import json
import random
import traceback
from datetime import datetime
import requests,string
from flask import Blueprint,Response,jsonify
from flask_restful import Api,Resource,reqparse,marshal
from common.models import db,rds
from common.models.user import UserModels
from werkzeug.security import generate_password_hash,check_password_hash
from common.model_fields.user_fields import user_fields
from celery_tasks.tasks import phone_code
import logging
from common.utils.jwt_utils import _generate_token
from sqlalchemy import or_
from captcha.image import ImageCaptcha

user_bp = Blueprint("user_bp",__name__,url_prefix='/user')
api = Api(user_bp)

# 图片验证码
class GenerateImgCode(Resource):
    def get(self,uuid):
        try:
            # 生成验证码
            salt = "".join(random.sample(string.ascii_letters + string.digits,4))

            # 生成验证码
            img = ImageCaptcha()
            image = img.generate(salt)

            key = "image_sms%s"%uuid

            rds.set(key,salt,ex= 60 * 5)

            return Response(image,mimetype="image/jpeg")
        except Exception as e:
            print("错误信息", e)
            return jsonify(message="服务器错误！", code=500)

# 发送短信验证码
class SendMessageCode(Resource):

    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('phone')
        args = parser.parse_args()
        phone = args.get('phone')

        #判断此手机号在短时间内是否重复发送
        if rds.get(phone):
            return {"message":"短信已经发送，别重新发送短信！"},409

        #生成验证码
        code = str(random.randint(100000,999999))
        #发送短信验证码
        try:
            rds.setex(phone,60,code)
            #发送短信
            result = json.loads(phone_code(phone,code))
            if result.get('statusCode') == '112310' or result.get('statusCode') == "000000":
                return {"message":"短信验证码发送成功",code:200}
            else:
                return {"message": "短信验证码发送失败", code: 400}
        except:
            error = traceback.format_exc()
            logging.error('meg error:{}'.format(error))
            return {'message': error, 'code': 500}

# 注册用户
class UserRegister(Resource):
    def _check_base_params(self,account,password,phone,confirm_password, code):
        """
               验证参数
               """
        if not all([account, password, phone, confirm_password, code]):
            return {'message': '参数不完整错误', 'code': 405}

        # 账号长度验证
        if len(account) > 20:
            return {'message': '账号长度不符合规则', 'code': 405}

        # 密码长度
        if len(password) > 20:
            return {'message': '密码太长', 'code': 405}

        if password != confirm_password:
            return {'message': '两次密码不一致', 'code': 405}
        # 从redis中取出短信验证码
        real_msg_code = rds.get(phone)
        # 判断是否存在 不存在
        if not real_msg_code:
            return {'code': 405, 'message': '验证码已过期'}
        real_msg_code = real_msg_code.decode()
        # 进行验证是否一致
        if real_msg_code != code:
            return {'code': 405, 'message': '验证码错误'}
        # 验证手机号是否已使用
        number = UserModels.query.filter_by(mobile=phone).count()
        if number >= 1:
            return {'code': 405, 'message': '手机号已绑定'}
        # 验证用户是否已经注册
        user = UserModels.query.filter_by(account=account).first()
        if user:
            return {'code': 405, 'message': '账号已存在'}
        return {'code': 200}
    def post(self):
        try:
            # 获取参数
            parser = reqparse.RequestParser()
            args_list = ['username', 'password', 'phone', 'code', 'password2']
            for args in args_list:
                parser.add_argument(args)
            args = parser.parse_args()
            account = args.get('username')
            password = args.get('password')
            confirm_password = args.get('password2')
            # 手机号
            phone = args.get('phone')
            # 手机验证码
            code = args.get('code')

            # 验证参数
            print(account, password, phone, confirm_password, code)
            check_result = self._check_base_params(account, password, phone, confirm_password, code)
            print('11111111111', check_result)
            if check_result['code'] != 200:
                return check_result

            # 通过验证，注册用户
            user = UserModels(account=account, password=generate_password_hash(password), mobile=phone)
            user.last_login_time = datetime.now()
            db.session.add(user)
            db.session.commit()
            return marshal(user, user_fields)
        except:
            error = traceback.format_exc()
            logging.error('register_user error:{}'.format(error))
            return {'error': error, 'code': 500}

# 登录
class UserLogin(Resource):
    def post(self):
        pars = reqparse.RequestParser()
        pars.add_argument("account")
        pars.add_argument('password')
        pars.add_argument('uuid')
        pars.add_argument('img_code')
        args = pars.parse_args()
        uuid = args.get('uuid')
        img_code = args.get('img_code')
        account = args.get('account')
        password = args.get('password')
        print(">>>>>~~~~打印出来的信息", account, password, uuid, img_code)

        user = UserModels.query.filter_by(account=account).first()

        return jsonify(message="登陆成功",code=200,data={
            "uid":user.uid,
            "account":user.account,
            "token": "asdadadada"
        })





api.add_resource(SendMessageCode,'/phone_code')
api.add_resource(UserRegister, '/register_user')
api.add_resource(GenerateImgCode,'/code/<uuid:uuid>')
api.add_resource(UserLogin,'/login')
